document.addEventListener('DOMContentLoaded', function() {
  // DOM元素引用
  const categoryTabs = document.getElementById('categoryTabs');
  const bookmarksContainer = document.getElementById('bookmarksContainer');
  const searchInput = document.getElementById('searchInput');
  const searchButton = document.getElementById('searchButton');
  const addBookmarkForm = document.getElementById('addBookmarkForm');
  
  // 全局状态
  let bookmarks = [];
  let filteredBookmarks = [];
  let currentCategory = '全部';
  let searchTerm = '';
  
  // 初始化应用
  async function init() {
    // 首先尝试从localStorage加载数据
    const savedData = localStorage.getItem('bookmarks');
    if (savedData) {
      const parsedData = JSON.parse(savedData);
      bookmarks = parsedData.bookmarks || [];
    } else {
      // 如果localStorage没有数据，则从JSON文件加载
      try {
        const response = await fetch('bookmarks.json');
        const data = await response.json();
        bookmarks = data.bookmarks || [];
        // 保存到localStorage
        saveToLocalStorage();
      } catch (error) {
        console.error('加载书签数据失败:', error);
        bookmarks = [];
      }
    }
    
    filteredBookmarks = [...bookmarks];
    renderCategoryTabs();
    renderBookmarks();
    setupEventListeners();
  }
  
  // 保存数据到localStorage
  function saveToLocalStorage() {
    localStorage.setItem('bookmarks', JSON.stringify({ bookmarks }));
  }
  
  // 渲染分类标签
  function renderCategoryTabs() {
    // 提取所有不重复的分类
    const categories = ['全部', ...new Set(bookmarks.map(bookmark => bookmark.category))];
    
    categoryTabs.innerHTML = '';
    
    categories.forEach(category => {
      const tab = document.createElement('div');
      tab.className = `category-tab ${currentCategory === category ? 'active' : ''}`;
      tab.textContent = category;
      tab.dataset.category = category;
      
      tab.addEventListener('click', () => {
        currentCategory = category;
        filterBookmarks();
        renderCategoryTabs(); // 重新渲染标签以更新active状态
      });
      
      categoryTabs.appendChild(tab);
    });
  }
  
  // 渲染书签列表
  function renderBookmarks() {
    bookmarksContainer.innerHTML = '';
    
    if (filteredBookmarks.length === 0) {
      // 显示空状态
      const emptyState = document.createElement('div');
      emptyState.className = 'empty-state';
      emptyState.innerHTML = `
        <div class="empty-state-icon">📂</div>
        <div class="empty-state-text">暂无书签</div>
      `;
      bookmarksContainer.appendChild(emptyState);
      return;
    }
    
    // 按分类分组显示
    const groupedBookmarks = {};
    
    if (currentCategory === '全部') {
      // 如果是全部分类，按类别分组
      filteredBookmarks.forEach(bookmark => {
        if (!groupedBookmarks[bookmark.category]) {
          groupedBookmarks[bookmark.category] = [];
        }
        groupedBookmarks[bookmark.category].push(bookmark);
      });
      
      // 遍历每个分类并渲染
      Object.keys(groupedBookmarks).forEach(category => {
        const categorySection = document.createElement('div');
        categorySection.className = 'category-section';
        
        const categoryHeader = document.createElement('h3');
        categoryHeader.className = 'category-header';
        categoryHeader.textContent = category;
        categorySection.appendChild(categoryHeader);
        
        const categoryBookmarks = document.createElement('div');
        categoryBookmarks.className = 'bookmarks-container';
        
        groupedBookmarks[category].forEach(bookmark => {
          categoryBookmarks.appendChild(createBookmarkCard(bookmark));
        });
        
        categorySection.appendChild(categoryBookmarks);
        bookmarksContainer.appendChild(categorySection);
      });
    } else {
      // 如果是特定分类，直接渲染
      filteredBookmarks.forEach(bookmark => {
        bookmarksContainer.appendChild(createBookmarkCard(bookmark));
      });
    }
  }
  
  // 创建书签卡片
  function createBookmarkCard(bookmark) {
    const card = document.createElement('a');
    card.href = bookmark.url;
    card.target = '_blank';
    card.rel = 'noopener noreferrer';
    card.className = 'bookmark-card';
    
    card.innerHTML = `
      <div class="bookmark-icon">${bookmark.icon || '🔗'}</div>
      <div class="bookmark-info">
        <div class="bookmark-name">${bookmark.name}</div>
        <div class="bookmark-url">${bookmark.url}</div>
      </div>
      <div class="bookmark-actions">
        <button type="button" class="action-button delete-button" data-id="${bookmark.id}">🗑️</button>
      </div>
    `;
    
    // 添加删除按钮事件
    const deleteButton = card.querySelector('.delete-button');
    deleteButton.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      deleteBookmark(bookmark.id);
    });
    
    return card;
  }
  
  // 筛选书签
  function filterBookmarks() {
    filteredBookmarks = bookmarks.filter(bookmark => {
      const matchesCategory = currentCategory === '全部' || bookmark.category === currentCategory;
      const matchesSearch = !searchTerm || 
        bookmark.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        bookmark.url.toLowerCase().includes(searchTerm.toLowerCase()) ||
        bookmark.category.toLowerCase().includes(searchTerm.toLowerCase());
      
      return matchesCategory && matchesSearch;
    });
    
    renderBookmarks();
  }
  
  // 删除书签
  function deleteBookmark(id) {
    if (confirm('确定要删除这个书签吗？')) {
      bookmarks = bookmarks.filter(bookmark => bookmark.id !== id);
      saveToLocalStorage();
      filterBookmarks();
    }
  }
  
  // 添加新书签
  function addBookmark(name, url, category) {
    const newBookmark = {
      id: Date.now(), // 使用时间戳作为唯一ID
      name,
      url: url.startsWith('http') ? url : `https://${url}`,
      category,
      icon: getCategoryIcon(category)
    };
    
    bookmarks.push(newBookmark);
    saveToLocalStorage();
    filterBookmarks();
    renderCategoryTabs(); // 更新分类标签
  }
  
  // 根据分类获取默认图标
  function getCategoryIcon(category) {
    const iconMap = {
      '搜索引擎': '🔍',
      '开发工具': '💻',
      '购物': '🛒',
      '娱乐': '🎵',
      '社交': '💬',
      '新闻': '📰',
      '视频': '🎬',
      '音乐': '🎶',
      '学习': '📚',
      '工具': '🧰'
    };
    
    return iconMap[category] || '🔗';
  }
  
  // 设置事件监听器
  function setupEventListeners() {
    // 搜索功能
    searchButton.addEventListener('click', () => {
      searchTerm = searchInput.value.trim();
      filterBookmarks();
    });
    
    searchInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        searchButton.click();
      }
    });
    
    // 添加书签表单
    addBookmarkForm.addEventListener('submit', (e) => {
      e.preventDefault();
      
      const siteName = document.getElementById('siteName').value.trim();
      const siteUrl = document.getElementById('siteUrl').value.trim();
      const siteCategory = document.getElementById('siteCategory').value.trim();
      
      if (siteName && siteUrl && siteCategory) {
        addBookmark(siteName, siteUrl, siteCategory);
        addBookmarkForm.reset();
        alert('书签添加成功！');
      }
    });
  }
  
  // 启动应用
  init();
});